<template>
  <el-card class="box-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <el-button
          class="button"
          type="primary"
          :icon="Plus"
          @click="trademark({ tmName: '', logoUrl: '' })">
          添加
        </el-button>
      </div>
    </template>
    <el-table ref="singleTableRef" :data="pageList" border style="width: 100%">
      <el-table-column type="index" width="80" label="序号" align="center" />
      <el-table-column property="tmName" label="品牌名称" />
      <el-table-column property="name" label="品牌LOGO">
        <template v-slot="{ row, $index }">
          <!-- row: 当前行数据对象 -->
          <el-image
            :src="row.logoUrl"
            style="width: 100px; height: 60px"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row, $index }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="trademark(row)"></el-button>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除"
            placement="top">
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="removeTrademark(row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="isShow"
      :title="trademarkForm.id ? '修改' : '添加'"
      width="40%">
      <el-form :model="trademarkForm" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="trademarkForm.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- action: 处理图片上传请求的url
                  不能直接写目标地址  => 跨域了
                  必须写一个带代理前缀路径的路径
            show-file-list: false  单个图片 -->
          <el-upload
            class="avatar-uploader"
            :action="`${VITE_BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img
              v-if="trademarkForm.logoUrl"
              :src="trademarkForm.logoUrl"
              class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShow = false">返回</el-button>
          <el-button type="primary" @click="confirms">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        style="margin-top: 20px"
        :page-sizes="[3, 6, 9]"
        layout="prev, pager, next, jumper,->, sizes, total"
        :total="total"
        @size-change="GetList"
        @current-change="GetList" />
    </div>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import type {
  trademarkModel,
  trademarksModel,
} from "@/api/product/model/trademarkModel";
import {
  getPageListApi,
  removeTrademarkApi,
  saveTrademarkApi,
  updateTrademarkApi,
} from "@/api/product/trademark";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  ElMessage,
  type UploadProps,
  type FormInstance,
  ElMessageBox,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";
const pageList = ref<trademarksModel>([]);
const currentPage = ref(1); // 当前页码
const pageSize = ref(3); // 每页数量
const total = ref(0); // 总数量

const GetList = async () => {
  const result = await getPageListApi(currentPage.value, pageSize.value);
  // console.log(result);
  pageList.value = result.records;
  total.value = result.total;
};
onMounted(() => {
  GetList();
});

const isShow = ref(false);
const VITE_BASE_URL = import.meta.env.VITE_BASE_URL;

const trademarkForm = ref<trademarkModel>({
  tmName: "",
  logoUrl: "",
});

const trademark = (row: trademarkModel) => {
  isShow.value = true;
  trademarkForm.value.id = row.id;
  trademarkForm.value.tmName = row.tmName;
  trademarkForm.value.logoUrl = row.logoUrl;

  // 清理错误验证 因为是异步的 所以放在定时器里面 或者两个nextTick
  setTimeout(() => {
    formRef.value?.clearValidate([]);
  }, 0);
};
const formRef = ref<FormInstance>();
// 表单校验规则列表
const rules = reactive({
  tmName: [
    { required: true, message: "品牌名称是必须的", trigger: "blur" }, // 必须的
    // 使用内置校验规则实现
    // {min: 3, max: 6, message: '品牌名称长必须在3到6位'/* , trigger: 'change' */}, // 长度必须是3到6位
    // 使用自定义校验来实现
    { validator: validateTmName, trigger: "change" },
  ],
  logoUrl: [{ required: true, message: "品牌LOGO是必须的" }],
});

function validateTmName(rule: any, value: any, callback: any) {
  if (value.length < 3 || value.length > 6) {
    // 如果校验不通过, 调用callback指定包含错误信息的error, 或者直接指定错误信息
    // callback(new Error('品牌名称长必须在3到6位'))
    callback("品牌名称长必须在3到6位!!!!");
  } else {
    // 校验通过时, 直接调用callback, 不传递任何参数
    callback();
  }
}

const confirms = () => {
  // 对表单进行统一校验
  formRef.value?.validate(async (valid) => {
    // valid校验是否通过
    // 校验成功后
    if (valid) {
      // 发添加/更新请求, 看trademarkForm.id是否有值
      if (trademarkForm.value.id) {
        await updateTrademarkApi(trademarkForm.value);
      } else {
        // saveTrademarkApi(trademarkForm.tmName, trademarkForm.logoUrl)
        await saveTrademarkApi(trademarkForm.value);
      }
      // 成功之后, 隐藏dialog, 重新获取列表显示, 提示添加或更新成功
      isShow.value = false;
      GetList();
      ElMessage.success(`${trademarkForm.value.id ? "更新" : "添加"}成功!`);
    }
  });
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  trademarkForm.value.logoUrl = response.data;
  // 清除logo的错误提示信息
  formRef.value?.clearValidate(["logoUrl"]);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/png" &&
    rawFile.type !== "image/gif"
  ) {
    ElMessage.error("只能上传jpg/png文件");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("不能超过50kB!");
    return false;
  }
  return true;
};

// 删除
const removeTrademark = async (id: number) => {
  ElMessageBox.confirm("确认是否删除?", {
    confirmButtonText: "确定",
    cancelButtonText: "返回",
    type: "success",
  })
    .then(async () => {
      await removeTrademarkApi(id);
      GetList();
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch((error) => {
      if (error === "cancel") {
        ElMessage({
          type: "info",
          message: "取消",
        });
      }
    });
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.tooltip-base-box {
  width: 600px;
}
.tooltip-base-box .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tooltip-base-box .center {
  justify-content: center;
}
.tooltip-base-box .box-item {
  width: 110px;
  margin-top: 10px;
}
</style>
